import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import moment from 'moment';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path) => reg.test(path);
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }

  return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env;

  if (NODE_ENV === 'development') {
    return true;
  }

  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(
    ({ routes, path = '/', target = '_self' }) =>
      (path && target !== '_blank' && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};
export const getRouteAuthority = (path, routeData) => {
  let authorities;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      } // exact match

      if (route.path === path) {
        authorities = route.authority || authorities;
      } // get children authority recursively

      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

export const formatNumber = (value) => {
  value += '';
  const list = value.split('.');
  const prefix = list[0].charAt(0) === '-' ? '-' : '';
  let num = prefix ? list[0].slice(1) : list[0];
  let result = '';
  while (num.length > 3) {
    result = `,${num.slice(-3)}${result}`;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
};

export const checkIdCard = (idCard) =>{
  // 格式错误返回true
  const format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
    //号码规则校验
    if(!format.test(idCard)){
      return true;
    }
    //区位码校验
    //出生年月日校验  前正则限制起始年份为1900;
  const year = idCard.substr(6,4),//身份证年
      month = idCard.substr(10,2),//身份证月
      date = idCard.substr(12,2),//身份证日
      time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
      now_time = Date.parse(new Date()),//当前时间戳
      dates = (new Date(year,month,0)).getDate();//身份证当月天数
    if(time>now_time||date>dates){
      return true;
    }
    //校验码判断
  const c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);  //系数
  const b = new Array('1','0','X','9','8','7','6','5','4','3','2'); //校验码对照表
  const id_array = idCard.split("");
    var sum = 0;
    for(var k=0;k<17;k++){
      sum+=parseInt(id_array[k])*parseInt(c[k]);
    }
    if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
      return true;
    }
    return false;
};

export const checkGender = (idCard) =>{
  if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
    return '1';
  } else {
    return '2';
  }
};

export const getBirthday = (idCard) =>{
  if(undefined != idCard){
    return idCard.substr(6, 4) + "-" + idCard.substr(10, 2) + "-" + idCard.substr(12, 2);
  }
};

export const checkPhone = (phone) =>{
  if(!(/^1[3456789]\d{9}$/.test(phone))){
    return true;
  }
};

export const resultDate = (contractBeginDate,value,timeType) =>{
  let temp = [];
  if(contractBeginDate){
    let month = moment(contractBeginDate).add(value,timeType).subtract(1,'days').month() + 1;
    let endTime;
    if(month <= 6){
      endTime = moment(contractBeginDate).subtract(1,'days').add(value,timeType).month(5).date(30);
    }else{
      endTime = moment(contractBeginDate).subtract(1,'days').add(value,timeType).month(11).date(31);
    }
    temp = [moment(contractBeginDate),endTime];
  }
  return temp;
};

/**
 * moment 时间相减
 * @param stm 开始时间
 * @param etm 结束时间
 */
export const subtractDate = (stm,etm) =>{
  let duration = moment.duration(moment(etm).add(1, 'd').diff(moment(stm)));
  return duration._data;
};

export const resultMonthDay = () =>{
  let temp = [];
  for (let i = 1; i < 32 ; i++) {
    temp.push({title:`每月${i}日`,value:i});
  }
  return temp;
};

export const checkImg = (item) => {
  let reg = /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$/;
  return reg.test(item);
};

export const resultCityName = (nativePlace,province,city) => {
  let temp = '';
  if(province){
    let cityArray = nativePlace.filter(item => item.value === parseInt(province))[0];
    temp += cityArray.title;
    if(cityArray.children){
      for(let it of cityArray.children){
        if(it.value === parseInt(city)){
          temp += it.title;
          return temp;
        }
      }
    }
  }
  return temp;
};

export const getSuffix = (url) => {
  if(checkImg(url)) return 'img';
  let suffix = url.split('.').pop().toLowerCase();
  return suffix;
};

export const getQueryString = (name) => {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.href.split('?')[1].match(reg);
  if (r != null) {
    return decodeURIComponent(r[2]);
  }
  return null;
};

export const resultSum = (list) => {
  let temp = 0;
  Object.values(list).forEach(item => {
    if(typeof item === 'number'){
      temp = temp += item;
    }
  });
  return temp;
};
/**
 * 计算字符串数字
 * @param list 对象values
 * @returns {number}
 */
export const resultStrSum = (list) => {
  let temp = 0;
  let sum = Object.values(list).filter(x => x !== undefined).length;
  Object.values(list).forEach(item => {
    if(item){
      temp = temp += parseInt(item);
    }
  });
  return temp === 0 ? 0 : (temp / sum).toFixed(2);
};

export const resultYearMonth = () =>{
  let temp = [];
  for (let i = 1; i <= 12 ; i++) {
    temp.push({label:`${i}月`,value:i});
  }
  return temp;
};
